<template>
  <div class="course-manage">
    <div class="course-flex font18 mb15">
      <div class="course-flex cursor-pointer">
        <div
          class="mr10"
          v-if="dialogState.form.stageOne"
          @click="handleStageType(dialogState.raceStageList[0])"
        >
          <span>{{
            RaceStageTypeText[dialogState.raceStageList[0].stageType]
          }}</span>
          <div
            class="course-line"
            :class="{
              action: isType === dialogState.raceStageList[0].stageType,
            }"
          ></div>
        </div>
        <div
          v-if="
            dialogState.form.stageTwo && dialogState.raceStageList.length === 2
          "
          @click="handleStageType(dialogState.raceStageList[1])"
        >
          <span>{{
            RaceStageTypeText[dialogState.raceStageList[1].stageType]
          }}</span>
          <div
            class="course-line"
            :class="{
              action: isType === dialogState.raceStageList[1].stageType,
            }"
          ></div>
        </div>
      </div>
      <div>
        <ExportButton :path="SCHEDULE_EXPORT_PATH" :fileName="SCHEDULE_EXPORT_FILE_NAME" :params="{raceId}" />
        <el-button type="primary" @click="handleManage">管理阶段</el-button>
        <el-button type="primary" @click="handleTeam">小组设置</el-button>
      </div>
    </div>

    <!-- 小组赛 - 设置 -->
    <el-radio-group
      v-if="
        isType === dialogState.raceStageList[0].stageType && !dialogState.isSave
      "
      v-model="isRace"
      style="margin-bottom: 30px"
      @change="handleGroup"
    >
      <el-radio-button label="1">小组分组</el-radio-button>
      <el-radio-button label="2">小组赛程</el-radio-button>
    </el-radio-group>

    <div v-loading="loading">
      <!-- 小组赛组件 -->
      <GroupComponent
        :form="dialogTeamState.form"
        :raceGroupList="raceGroupList"
        :raceTeamList="raceTeamList"
        v-if="isType === 'group' && isRace === '1'"
      />
      <CourseComponent
        :raceGroupScheduleList="raceGroupScheduleList"
        :raceTeamList="raceTeamList"
        :raceRoleList="raceRoleList"
        @getRaceGroupSchedule="getRaceGroupScheduleInfo"
        v-if="isType === 'group' && isRace === '2'"
      />
      <!-- 排位赛组件 -->
      <TurnComponent
        :raceGroupScheduleList="raceGroupScheduleList"
        :raceTeamList="raceTeamList"
        :raceRoleList="raceRoleList"
        :raceGroupId="raceGroupId"
        @getRaceGroupSchedule="getRaceGroupScheduleInfo"
        v-if="dialogState.form.stageTwo && isType === 'qualifier'"
      />
    </div>

    <!-- 小组赛事阶段管理 -->
    <el-dialog
      v-model="dialogState.dialogVisible"
      title="赛事阶段管理"
      width="40%"
    >
      <el-form :model="dialogState.form" ref="formRef" label-width="120px">
        <el-form-item
          prop="stageOne"
          label="阶段一："
          :rules="[
            {
              required: true,
              message: '请输入阶段一',
              trigger: 'blur',
            },
          ]"
        >
          <el-select
            v-model="dialogState.form.stageOne"
            class="m-2"
            style="width: 100%"
            placeholder="请选择阶段一"
          >
            <el-option label="小组赛" :value="RaceStageTypeEnum.GROUP" />
          </el-select>
        </el-form-item>
        <el-form-item prop="stageTwo" label="阶段二：">
          <el-select
            v-model="dialogState.form.stageTwo"
            class="m-2"
            style="width: 100%"
            clearable
            placeholder="请选择阶段二（非必填）"
          >
            <el-option label="排位赛" :value="RaceStageTypeEnum.QUALIFIER" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleCancel(formRef)">取消</el-button>
          <el-button type="primary" @click="submitForm(formRef)">
            确认
          </el-button>
        </span>
      </template>
    </el-dialog>
    <!-- 小组设置 -->
    <el-dialog
      v-model="dialogTeamState.dialogTeamVisible"
      title="赛事阶段管理"
      width="40%"
    >
      <el-form
        :model="dialogTeamState.form"
        ref="formTeamRef"
        label-width="120px"
      >
        <el-form-item prop="groupCount" label="小组数量：">
          <el-input
            v-model.number="dialogTeamState.form.groupCount"
            placeholder="请输入小组数量"
          />
        </el-form-item>
        <el-form-item prop="teamCount" label="球队数量：">
          <el-input
            v-model.number="dialogTeamState.form.teamCount"
            placeholder="请输入球队数量"
          />
        </el-form-item>
        <el-form-item prop="groupStageType" label="小组赛形式：">
          <el-select
            v-model="dialogTeamState.form.groupStageType"
            class="m-2"
            style="width: 100%"
            placeholder="请选择小组赛形式"
          >
            <el-option
              v-for="item in courseGroupList"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item prop="advanceCount" label="出线球队数量：">
          <el-input
            v-model.number="dialogTeamState.form.advanceCount"
            placeholder="请输入出线球队数量"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleTeamCancel(formTeamRef)">取消</el-button>
          <el-button type="primary" @click="submitTeamForm(formTeamRef)">
            确认
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { onMounted, reactive, ref } from "vue";
import type { FormInstance } from "element-plus";
import { useRoute } from "vue-router";
import {
  getRace,
  saveRace,
  updateRace,
  getRaceConfig,
  saveRaceConfig,
  updateRaceConfig,
  getRaceGroup,
  getRaceGroupSchedule,
  getTeamList,
  getRaceRoleList,
} from "@/api/match";
import { ElMessage } from "element-plus";
import { RaceStageTypeText } from "../../config/index";
import { RaceStageTypeEnum } from "../../config/enum";
import { courseGroupList } from "../../config/courseMock";
import GroupComponent from "./components/groupComponent.vue";
import CourseComponent from "./components/courseComponent.vue";
import TurnComponent from "./components/turnComponent.vue";
import ExportButton from '@/components/ExportButton/index.vue'
import { SCHEDULE_EXPORT_PATH, SCHEDULE_EXPORT_FILE_NAME} from '@/components/ExportButton/config'

const route = useRoute();
const formRef = ref<FormInstance>();
const formTeamRef = ref<FormInstance>();
const isType = ref("group"); // 小组赛、排位赛标识
const raceGroupId = ref(); // 小组赛/排位赛id
const isRace = ref("1");
const loading = ref(false); // 当前赛事的id
const raceId = ref(0); // 当前赛事的id
const raceTeamList = ref([]); // 球队数据
const raceGroupList = ref([]); // 小组赛数据
const raceGroupScheduleList = ref([]); // 小组赛-赛程数据
const raceRoleList = ref([]); // 赛程配置基础数据
const dialogState = reactive({
  dialogVisible: false,
  form: {
    stageOne: "",
    stageTwo: "",
  },
  isSave: true,
  raceStageList: [
    {
      stageType: "", //阶段类型
      stageOrder: 1, //排序
    },
    {
      stageType: "", //阶段类型
      stageOrder: 2, //排序
    },
  ],
});
const dialogTeamState = reactive({
  dialogTeamVisible: false,
  isSave: true,
  form: {
    groupCount: "", //小组数量
    teamCount: "", //球队数量
    groupStageType: "", //小组赛类型
    advanceCount: "", //出线球队数量
  },
});

// 赛程切换
const handleStageType = (value: any) => {
  isType.value = value.stageType;
  raceGroupId.value = value.raceStageId;
  (raceGroupScheduleList.value = []), (isRace.value = "1"); // 初始化数据
  if (isType.value === "qualifier") {
    handleGroup("0");
  } else {
    handleGroup("1");
  }
};
// 小组 分组/赛程切换
const handleGroup = async (value: string) => {
  isRace.value = value;
  if (value === "1") {
    await getRaceGroupInfo();
  } else {
    await getRaceGroupScheduleInfo();
  }
  getRaceGroupList();
};
// 赛事阶段管理
const handleManage = async () => {
  await getRaceList();
  dialogState.dialogVisible = true;
};
const handleCancel = (formEl: FormInstance | undefined) => {
  dialogState.dialogVisible = false;
  if (!formEl) return;
  formEl.resetFields();
};
const submitForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.validate(async (valid) => {
    if (valid) {
      dialogState.raceStageList.map((item) => {
        if (item.stageOrder === 1) {
          item.stageType = dialogState.form.stageOne;
        } else {
          item.stageType = dialogState.form.stageTwo;
        }
      });
      if (dialogState.form.stageTwo === "") {
        dialogState.raceStageList.splice(1, 1);
      } else if (
        dialogState.form.stageTwo != "" &&
        dialogState.raceStageList.length === 1
      ) {
        dialogState.raceStageList.push({
          stageType: dialogState.form.stageTwo,
          stageOrder: 2,
        });
      }
      let res;
      if (dialogState.isSave) {
        res = await saveRace({
          raceId: raceId.value,
          raceStageList: dialogState.raceStageList,
        });
      } else {
        res = await updateRace({
          raceStageList: dialogState.raceStageList,
        });
      }
      ElMessage.success(res.msg);
      getRaceList();
      dialogState.dialogVisible = false;
    } else {
      console.log("error submit!");
      return false;
    }
  });
};
// 小组设置
const handleTeam = async () => {
  await getRaceInfo();
  dialogTeamState.dialogTeamVisible = true;
};
const handleTeamCancel = (formEl: FormInstance | undefined) => {
  dialogTeamState.dialogTeamVisible = false;
  if (!formEl) return;
  formEl.resetFields();
};
const submitTeamForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.validate(async (valid) => {
    if (valid) {
      let res;
      if (dialogTeamState.isSave) {
        if (dialogState.raceStageList[0].stageType) {
          let params = {
            raceStageId: raceGroupId.value,
            ...dialogTeamState.form,
          };
          res = await saveRaceConfig(params);
        } else {
          return ElMessage.warning("请优先设置管理阶段！");
        }
      } else {
        res = await updateRaceConfig(dialogTeamState.form);
      }
      ElMessage.success(res.msg);
      getRaceGroupInfo();
      dialogTeamState.dialogTeamVisible = false;
      formEl.resetFields();
    } else {
      console.log("error submit!");
      return false;
    }
  });
};
// 初始化 - 管理阶段
const getRaceList = async () => {
  const res = await getRace({ raceId: raceId.value });
  if (res.data.length != 0) {
    dialogState.raceStageList = res.data;
    res.data.map((item: any) => {
      if (item.stageOrder === 1) {
        raceGroupId.value = item.raceStageId;
        dialogState.form.stageOne = item.stageType;
      } else {
        dialogState.form.stageTwo = item.stageType || "";
      }
    });
    dialogState.isSave = false;
  }
};
// 初始化 - 小组设置数据
const getRaceInfo = async () => {
  const res = await getRaceConfig({ raceId: raceId.value });
  if (res.data.teamCount != null) {
    dialogTeamState.form = { ...res.data };
    dialogTeamState.isSave = false;
    handleGroup("1");
  }
};
// 初始化 - 小组分组数据
const getRaceGroupInfo = async () => {
  loading.value = true;
  const res = await getRaceGroup({ raceStageId: raceGroupId.value });
  console.log("小组", res.data, raceGroupId.value);
  loading.value = false;
  raceGroupList.value = res.data || [];
};
// 初始化 - 小组赛程数据
const getRaceGroupScheduleInfo = async () => {
  loading.value = true;
  const res = await getRaceGroupSchedule({ raceStageId: raceGroupId.value });
  console.log("赛程", res.data, raceGroupId.value);
  loading.value = false;
  raceGroupScheduleList.value = res.data || [];
};

/**
 * 获取球队列表
 */
const fetchTeamList = async () => {
  getTeamList({
    raceId: raceId.value,
    teamName: "",
    auditStatus: "completed",
  }).then((res) => {
    raceTeamList.value = res.data || [];
  });
};

/**
 * 获取赛程配置信息
 */
const getRaceGroupList = () => {
  getRaceRoleList().then((res) => {
    raceRoleList.value = res.data;
  });
};

// 初始化数据
onMounted(async () => {
  let { id } = route.query;
  raceId.value = Number(id);
  await fetchTeamList();
  await getRaceList();
  await getRaceInfo();
});
</script>

<style lang="scss" scoped>
.course-manage {
  background-color: white;

  .course-flex {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  .course-line {
    width: 20px;
    height: 2px;
    margin: 0 auto;
    margin-top: 4px;
  }

  .action {
    background-color: var(--color-primary);
  }
}
</style>
